//
//  LCPlayViewController.m
//  TheLCNews
//
//  Created by apple on 15/12/4.
//  Copyright © 2015年 LC. All rights reserved.
//

#import "LCPlayViewController.h"
#import "Lcdada.h"
#import "Lchao.h"
typedef NS_ENUM(NSInteger, PlayMode)
{
    OneSongMode = 0,//单曲循环
    RandomMode,//随机播放
    OrderMode//顺序播放
};
@interface LCPlayViewController ()<UITableViewDataSource, UITableViewDelegate, STKAudioPlayerDelegate>
@property (nonatomic, assign)PlayMode playMode; // 播放类型 枚举
@property (nonatomic, retain) LCCoreDateManager *manager;

@end

@implementation LCPlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self startTime];
    self.tempArray = [NSArray array];
    self.manager = [LCCoreDateManager defaults];
    self.player = [[STKAudioPlayer alloc]initWithOptions:(STKAudioPlayerOptions){
        .flushQueueOnSeek = YES,
        .enableVolumeMixer = YES
    }];
    self.player.delegate = self;
    self.titleNameArr = @[@"正在播放", @"推荐列表", @"喜欢的音乐", @"历史播放列表", @"分享您喜欢的"];
    self.backImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
    [self.backImageView sd_setImageWithURL:[NSURL URLWithString:self.pic] placeholderImage:[UIImage imageNamed:@""]];
    self.backImageView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
    [self.view addSubview:self.backImageView];
    //增加模糊效果
    UIVisualEffectView *visual = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle: UIBlurEffectStyleDark]];
    visual.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
    [self.backImageView addSubview:visual];
    visual.alpha = 1;
   
    //tableVIew上面部分
    [self createHeadView];
    //tableVIew下面部分
    [self createButtonView];
    [self createTableView];
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:self.backButton];
    self.backButton.frame = CGRectMake(10,  25,  25,  25);
    [self.backButton setImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    //刚进这个页面，让他处于播放的状态
    if (self.player.state == STKAudioPlayerStatePaused) {
        [self.nowPlayLable setText:@"播放暂停"];
        self.player.state = STKAudioPlayerStatePlaying;
    }if (self.player.state == STKAudioPlayerStatePlaying) {
        [self.nowPlayLable setText:@"正在播放"];
        [self givePicToplayButtonWhenPlay];
        [self loadPlayData];
        self.player.state = STKAudioPlayerStatePlaying;
    }else{
        [self givePicToplayButtonWhenPlay];
        [self.nowPlayLable setText:@"正在播放"];
        [self loadPlayData];
        self.player.state = STKAudioPlayerStatePlaying;
    }
    NSLog(@"%@", self.manager.applicationDocumentsDirectory);
}

#pragma mark 解析播放数据
-(void)loadPlayData{
    [self.player play:self.playUrl];
    //点上一首下一首换图片
    [self secondGiveData];
    //播放时长
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
}
#pragma mark 播放单例
+(LCPlayViewController *)sharePlayer{
    static LCPlayViewController *player;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[LCPlayViewController alloc] init];
    });
    return  player;
}
#pragma mark - 外部调用方法
- (void)setData:(NSMutableArray *)songs row:(NSInteger)row
{
    //如果当前播放的音乐就是传入的音乐，那么就直接返回
    //判断暂停进来的时候是否是同一首歌
    if (self.playUrl == [[songs objectAtIndex:row] source]){
        if (self.player.state == STKAudioPlayerStatePaused) {
            [self.player play:[[songs objectAtIndex:row] source]];
        }
        return;
    }
    //如果不是同一首歌
    else{
        //播放按钮加图片
        [self givePicToplayButtonWhenPlay];
    }
    self.player.delegate = self;
    self.allMusicArray = [[NSMutableArray alloc]init];
    self.allMusicArray = songs;
    self.indexRow = row;
    [self loadPlayData];
}
//返回按钮
- (void)backButtonClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}
//tableView上面部分
- (void)createHeadView
{
    self.headPicImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mine"]];
    self.headPicImageView.frame = CGRectMake( 20,  50,  90,  90);
    [self.view addSubview:self.headPicImageView];
    self.headPicImageView.layer.masksToBounds = YES;
    self.headPicImageView.layer.cornerRadius = WIDTH / 375 * 45;
    //给头像赋值
    [self.headPicImageView sd_setImageWithURL:[NSURL URLWithString:[[self.allMusicArray objectAtIndex:self.indexRow] pic]] placeholderImage:[UIImage imageNamed:@"mine"]];
    UIImageView *lineImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mine"]];
    [self.headPicImageView addSubview:lineImageView];
    lineImageView.frame = CGRectMake(-WIDTH / 375 * 6.5, -HEIGHT / 667 * 6.8, WIDTH / 375 * 102.8, WIDTH / 375 * 102.8);
    lineImageView.alpha = 0.7;
    self.headTitleNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 375 * 30 + self.headPicImageView.frame.size.width, HEIGHT / 667 * 60, WIDTH / 375 * 220, HEIGHT / 667 * 60)];
    self.headTitleNameLabel.numberOfLines = 2;
    [self.view addSubview:self.headTitleNameLabel];
    self.headTitleNameLabel.textColor = [UIColor whiteColor];
    self.headTitleNameLabel.font = [UIFont systemFontOfSize:15 * HEIGHT / 667 weight:12];
    self.headTitleNameLabel.text = @"标题啊";
    self.headNamelabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 375 * 30 + self.headPicImageView.frame.size.width, WIDTH / 375 * 55 + self.headTitleNameLabel.frame.size.height, WIDTH / 375 * 200, HEIGHT / 667 * 30)];
    [self.view addSubview:self.headNamelabel];
    self.headNamelabel.textColor = [UIColor lightGrayColor];
    self.headNamelabel.font = [UIFont systemFontOfSize:14];
//    self.headNamelabel.text = @"1111";
    self.nowPlayLable = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH/ 375 * 150, HEIGHT / 667 * 10, WIDTH / 375 * 100, HEIGHT / 667 * 50)];
    [self.nowPlayLable setText:@"正在播放"];
    [self.nowPlayLable setFont:[UIFont systemFontOfSize:15]];
    [self.nowPlayLable setTextColor:[UIColor whiteColor]];
    [self.view addSubview:self.nowPlayLable];
    
    //收藏
//    self.saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [self.saveButton setFrame:CGRectMake(self.view.frame.size.width - WIDTH / 375 * 30, 25 * HEIGHT / 667, WIDTH / 375 * 20, HEIGHT / 667 * 20)];
//    [self.saveButton addTarget:self action:@selector(saveButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self.saveButton setBackgroundImage:[UIImage imageNamed:@"like"] forState:UIControlStateNormal];
//    [self.saveButton setBackgroundImage:[UIImage imageNamed:@"liked"] forState:UIControlStateSelected];
//    [self.saveButton setTag:self.indexRow];
//    [self.saveButton setSelected:NO];
//    [self search];
//    for (Lcdada *temopModel in self.tempArray) {
//        if ([temopModel.source isEqualToString:self.playUrl]) {
//            [self.saveButton setSelected:YES];
//        }else{
//        }
//    }
//    [self.view addSubview:self.saveButton];
}

#pragma mark 收藏功能
//-(void)saveButtonAction:(UIButton *)button{
//    int count = 0;
//
//    if (self.tempArray.count == 0) {
//        Lcdada *list = [NSEntityDescription insertNewObjectForEntityForName:@"Lcdada" inManagedObjectContext:self.manager.managedObjectContext];
//        list.name = [[self.allMusicArray objectAtIndex:self.indexRow] name];
//        list.pic =[[self.allMusicArray objectAtIndex:self.indexRow] pic];
//        list.source = self.playUrl;
//        [self.manager saveContext];
//    }
//    else{
//        for (Lcdada *modelll in self.tempArray) {
//            if (![modelll.source isEqualToString:self.playUrl]) {
//                count++;
//            }
//        }
//        if (count == self.tempArray.count) {
//            Lcdada *list = [NSEntityDescription insertNewObjectForEntityForName:@"Lcdada" inManagedObjectContext:self.manager.managedObjectContext];
//            list.name = [[self.allMusicArray objectAtIndex:self.indexRow] name];
//            list.pic = [[self.allMusicArray objectAtIndex:self.indexRow] pic];
//            list.source = self.playUrl;
//            [self.manager saveContext];
//        }
//    }
//    if (!button.selected) {
//        button.selected = YES;
//    }
//    else{
//        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
//        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Lcdada" inManagedObjectContext:self.manager.managedObjectContext];
//        [fetchRequest setEntity:entity];
//        NSError *error = nil;
//        NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
//        if (fetchedObjects == nil) {
//        }else{
//            for (Lcdada *list in fetchedObjects) {
//                if ([list.source isEqualToString:self.playUrl]) {
//                    [self.manager.managedObjectContext deleteObject:list];
//                }
//            }
//        }
//        [self.manager saveContext];
//        button.selected = NO;
//    }
//}
- (void)createButtonView
{
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(WIDTH / 375 * 30, HEIGHT / 667 * 520, WIDTH  - WIDTH / 375 * 60, HEIGHT / 667 * 20)];
    UIImage *thumbImage = [UIImage imageNamed:@"mine"];
    [self.slider setThumbImage:thumbImage forState:UIControlStateHighlighted];
    [self.slider setThumbImage:thumbImage forState:UIControlStateNormal];
    [self.slider addTarget:self action:@selector(slideAction:) forControlEvents:UIControlEventValueChanged];
//    self.slider.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.slider];
    
    self.labelBeginTim = [[UILabel alloc] initWithFrame:CGRectMake(self.slider.frame.origin.x, self.slider.frame.size.height + self.slider.frame.origin.y + 5 * HEIGHT / 667, 40 * WIDTH / 375, 20 * HEIGHT / 667)];
    self.labelBeginTim.font = [UIFont systemFontOfSize:13 * HEIGHT / 667];
    [self.labelBeginTim setTextColor:[UIColor whiteColor]];
    
    [self.view addSubview:self.labelBeginTim];
    
    self.labelBEndTim = [[UILabel alloc] initWithFrame:CGRectMake(self.labelBeginTim.frame.origin.x + WIDTH / 375 * 270, self.labelBeginTim.frame.origin.y, self.labelBeginTim.frame.size.width, self.labelBeginTim.frame.size.height)];
    self.labelBEndTim.font = [UIFont systemFontOfSize:13 * HEIGHT / 667];
    [self.labelBEndTim setTextColor:[UIColor whiteColor]];
    
    [self.view addSubview:self.labelBEndTim];
    //这是播放顺序的
    self.circleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.circleButton.frame = CGRectMake(WIDTH / 375 * 70, HEIGHT / 667 * 580, WIDTH / 375 * 23, WIDTH / 375 * 23);
//    self.circleButton.imageView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.circleButton];
//    [self.circleButton setImage:[UIImage imageNamed:@"sunxu"] forState:UIControlStateNormal];
    [self.circleButton addTarget:self action:@selector(circleButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self circleButtonClicked:self.circleButton];
    
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:self.playButton];
//    [self.playButton setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
    self.playButton.frame = CGRectMake(WIDTH / 375 * 170, HEIGHT / 667 * 573, WIDTH / 375 * 40, WIDTH / 375 * 40);
    [self.playButton addTarget:self action:@selector(playButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    if (self.playUrl == [[self.allMusicArray objectAtIndex:self.indexRow] source]){
        if (self.player.state == STKAudioPlayerStatePaused) {
            [self givePicToplayButtonWhenPause];
        }
        if(self.player.state == STKAudioPlayerStatePlaying)
        {
            [self givePicToplayButtonWhenPlay];
        }
        else{
            if (self.playUrl == [[self.allMusicArray objectAtIndex:self.indexRow] source]){
                [self givePicToplayButtonWhenPlay];
            }else{
                [self givePicToplayButtonWhenPause];
            }
        }
    }
    //上一曲下一曲
    self.previousButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:self.previousButton];
    self.previousButton.frame = CGRectMake(WIDTH / 375 * 110, HEIGHT / 667 * 575, WIDTH / 375 * 35, WIDTH / 375 * 35);
    [self.previousButton setImage:[UIImage imageNamed:@"up"] forState:UIControlStateNormal];
    [self.previousButton addTarget:self action:@selector(previousButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:self.nextButton];
    self.nextButton.frame = CGRectMake(WIDTH / 375 * 240, HEIGHT / 667 * 575, WIDTH / 375 * 35, WIDTH / 375 * 35);
    [self.nextButton setImage:[UIImage imageNamed:@"next"] forState:UIControlStateNormal];
    [self.nextButton addTarget:self action:@selector(nextButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.voiceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:self.voiceButton];
    self.voiceButton.frame = CGRectMake(WIDTH / 375 * 290, HEIGHT / 667 * 577, WIDTH / 375 * 30, WIDTH / 375 * 30);
    [self.voiceButton setImage:[UIImage imageNamed:@"laba"] forState:UIControlStateNormal];
    [self.voiceButton addTarget:self action:@selector(voiceButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
#pragma mark 创建声音的进度条
    self.sliderVolumeProgress = [[UISlider alloc] initWithFrame:CGRectMake(100.f * WIDTH / 375 , self.view.frame.size.height + HEIGHT / 667 * 30, WIDTH / 375 * 175.f, HEIGHT / 667 * 15.f)];
    [self.sliderVolumeProgress setThumbImage:[UIImage imageNamed:@"laba1"] forState:UIControlStateNormal];
    self.sliderVolumeProgress.value = 0.5;
    [self.sliderVolumeProgress addTarget:self action:@selector(volumeAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.sliderVolumeProgress];
    
}
//播放时长
-(void)timeAction{
    //总时长
    self.slider.maximumValue = self.player.duration;
    //当前
    self.slider.value = self.player.progress ;
    //分
    NSInteger proMin = (NSInteger)self.player.progress / 60;
    //秒
    NSInteger proSec = (NSInteger)self.player.progress % 60;
    NSInteger durMin = (NSInteger)(self.player.duration )/ 60;
    NSInteger durSec = (NSInteger)(self.player.duration )% 60;
    self.labelBeginTim.text = [NSString stringWithFormat:@"%02ld:%02ld",proMin, proSec];
    self.labelBEndTim.text = [NSString stringWithFormat:@"%02ld:%02ld", durMin, durSec];
}

//播放
- (void)playButtonClicked:(UIButton *)sender
{
    //暂停
    if (self.player.state == STKAudioPlayerStatePaused) {
        [self givePicToplayButtonWhenPlay];
        //继续播放
        [self.player resume];
        self.nowPlayLable.text = @"正在播放";
        //让计时器开始
        [self.musicTime setFireDate:[NSDate distantPast]];
        //当前是播放状态
    }else if (self.player.state == STKAudioPlayerStatePlaying){
        [self givePicToplayButtonWhenPause];
        [self.player pause];
        self.nowPlayLable.text = @"播放暂停";
        //让计时器暂停
        [self.musicTime setFireDate:[NSDate distantFuture]];
    }else{
        [self givePicToplayButtonWhenPause];
        [self loadPlayData];
    }
}
#pragma mark 进度条
-(void)slideAction:(UISlider *)slider{
    if (self.player) {
        //把player的进度值给播放进度条
        [self.player seekToTime:slider.value];
    }
}
#pragma mark 历史
-(void)addHistory{
    int count = 0;
    if (self.searchHistoryArray.count == 0) {
        Lchao *list = [NSEntityDescription insertNewObjectForEntityForName:@"Lchao" inManagedObjectContext:self.manager.managedObjectContext];
        list.name = [[self.allMusicArray objectAtIndex:self.indexRow] name];
        list.pic =[[self.allMusicArray objectAtIndex:self.indexRow] pic];
        list.source = self.playUrl;
        [self.manager saveContext];
    }
    else{
        for (Lchao *modelll in self.searchHistoryArray) {
            if (![modelll.source isEqualToString:[self.allMusicArray[self.indexRow] source]]) {
                count++;
            }
        }
        if (count == self.searchHistoryArray.count) {
            Lchao *list = [NSEntityDescription insertNewObjectForEntityForName:@"Lchao" inManagedObjectContext:self.manager.managedObjectContext];
            list.name = [[self.allMusicArray objectAtIndex:self.indexRow] name];
            list.pic = [[self.allMusicArray objectAtIndex:self.indexRow] pic];
            list.source = self.playUrl;
            [self.manager saveContext];
        }
    }
}
//上一曲
- (void)previousButtonClicked:(UIButton *)sender
{
    if (self.player.state == STKAudioPlayerStatePaused) {
        [self.nowPlayLable setText:@"正在播放"];
        if (self.playMode == OrderMode){
            self.indexRow--;
            //    判断当前是否是第一曲,如果是第一曲,点击后一直播放播放第一曲
            if (self.indexRow <= 0) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                self.player.state = STKAudioPlayerStatePaused;
                //播放
                [self givePicToplayButtonWhenPlay];
                //解析数据那里
                [self loadPlayData];
                [self.tableView reloadData];
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self.player pause];
                self.player.state = STKAudioPlayerStatePlaying;
                [self givePicToplayButtonWhenPlay];
                [self loadPlayData];
            }
        }
        if (self.playMode == RandomMode) {
            self.indexRow = arc4random() % self.allMusicArray.count;
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            [self givePicToplayButtonWhenPlay];
            [self loadPlayData];
        }
        if (self.playMode == OneSongMode) {
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow--] source];
            [self givePicToplayButtonWhenPlay];
            [self loadPlayData];
        }
    }
    //如果当前是播放状态
    else{
        [self.nowPlayLable setText:@"正在播放"];
        if (self.playMode == OrderMode){
            self.indexRow--;
            //   判断当前是否是最后一曲,如果是最后一曲,点击后重新播放第一曲
            if (self.indexRow <= 0) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                //点击下一曲重新给歌曲名和图片复制
                [self loadPlayData];
            }
        }
        if (self.playMode == RandomMode) {
            self.indexRow = arc4random() % self.allMusicArray.count;
            if (self.indexRow <= 0) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                //点击下一曲重新给歌曲名和图片复制
                [self loadPlayData];
            }
        }
        if (self.playMode == OneSongMode) {
            if (self.indexRow <= 0) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow--] source];
                //点击下一曲重新给歌曲名和图片复制
                [self loadPlayData];
            }
        }
    }
    [self search];
    for (Lcdada *temopModel in self.tempArray) {
        if ([temopModel.source isEqualToString:self.playUrl]) {
            [self.saveButton setSelected:YES];
        }else{
            [self.saveButton setSelected:NO];
        }
    }
    [self.tableView reloadData];
    [self searchHistory];
    [self addHistory];
}
//下一曲
- (void)nextButtonClicked:(UIButton *)sender
{
    if (self.player.state == STKAudioPlayerStatePaused) {
        [self.nowPlayLable setText:@"正在播放"];
        if (self.playMode == OrderMode){
            self.indexRow++;
            //    判断当前是否是最后一曲,如果是最后一曲,点击后重新播放第一曲
            if (self.indexRow == self.allMusicArray.count) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                self.player.state = STKAudioPlayerStatePlaying;
                [self givePicToplayButtonWhenPlay];
                [self loadPlayData];
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self.player pause];
                [self givePicToplayButtonWhenPlay];
                [self loadPlayData];
            }
        }
        if (self.playMode == RandomMode) {
            self.indexRow = arc4random() % self.allMusicArray.count;
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            [self givePicToplayButtonWhenPlay];
            [self loadPlayData];
        }
        if (self.playMode == OneSongMode) {
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow++] source];
            [self givePicToplayButtonWhenPlay];
            [self loadPlayData];
        }
    }
    //当是播放状态时
    else{
        [self.nowPlayLable setText:@"正在播放"];
        if (self.playMode == OrderMode){
            self.indexRow++;
            //   判断当前是否是最后一曲,如果是最后一曲,点击后重新播放第一曲
            if (self.indexRow == self.allMusicArray.count) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                //点击下一曲重新给歌曲名和图片复制
                [self secondGiveData];
                NSLog(@"!!!!!!!!!!!!%ld", self.indexRow);
                [self loadPlayData];
            }
        }
        if (self.playMode == RandomMode) {
            self.indexRow = arc4random() % self.allMusicArray.count;
            NSLog(@"!!!!!!!!!!!!%ld", self.indexRow);
            if (self.indexRow == self.allMusicArray.count) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                //点击下一曲重新给歌曲名和图片复制
                [self loadPlayData];
            }
        }
        if (self.playMode == OneSongMode) {
            if (self.indexRow == self.allMusicArray.count) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow++] source];
                //点击下一曲重新给歌曲名和图片复制
                NSLog(@"!!!!!!!!!!!!%ld", self.indexRow);
                [self loadPlayData];
            }
        }
    }
    [self search];
    for (Lcdada *temopModel in self.tempArray) {
        if ([temopModel.source isEqualToString:self.playUrl]) {
            [self.saveButton setSelected:YES];
        }else{
            [self.saveButton setSelected:NO];
        }
    }
    [self.tableView reloadData];
    [self searchHistory];
    [self addHistory];
}
//循环模式
- (void)circleButtonClicked:(UIButton *)sender
{
    if (self.playMode == OrderMode) {
        [self.circleButton setBackgroundImage:[UIImage imageNamed:@"sunxu"] forState:UIControlStateNormal];
        self.playMode = OneSongMode;
    }else if (self.playMode == OneSongMode) {
        [self.circleButton setBackgroundImage:[UIImage imageNamed:@"one"] forState:UIControlStateNormal];
        self.playMode = RandomMode;
    }else{
        [self.circleButton setBackgroundImage:[UIImage imageNamed:@"suiji"] forState:UIControlStateNormal];
        self.playMode = OrderMode;
    }
}
- (void)volumeAction:(UISlider *)sender{
    //    把player的进度值给声音进度条
    self.player.volume = sender.value;
}
//调节音量
- (void)voiceButtonClicked:(UIButton *)sender
{
    sender.selected = !sender.isSelected;
    if (sender.isSelected) {
        [UIView animateWithDuration:0.2 animations:^{
            self.sliderVolumeProgress.frame = CGRectMake(100 * HEIGHT / 667, self.view.frame.size.height - 50.f * HEIGHT / 667, 150 * HEIGHT / 667 , 35.f * HEIGHT / 667);
        }];
    }else{
        [UIView animateWithDuration:0.2 animations:^{
            self.sliderVolumeProgress.frame = CGRectMake(0, self.view.frame.size.height + 35.f,  self.view.frame.size.width, 35.f);
        }];
    }
}
#warning 摇一摇
- (BOOL)canBecomeFirstResponder
{
    return YES;
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self becomeFirstResponder];
}
#pragma mark - 实现相应的响应者方法
/** 开始摇一摇 */
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"motionBegan");
    [self nextSong];
    
    //摇一摇之后计时器开始
    [self.musicTime setFireDate:[NSDate distantPast]];
}
#pragma mark下一曲
-(void)nextSong{
    if (self.player.state == STKAudioPlayerStatePaused) {
        if (self.playMode == OrderMode){
            self.indexRow++;
            //加图片
            [self givePicToplayButtonWhenPlay];
            
            if (self.indexRow == self.allMusicArray.count) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                self.player.state = STKAudioPlayerStatePlaying;
                //    判断当前是否是最后一曲,如果是最后一曲,点击后重新播放第一曲
                [self loadPlayData];
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self.player pause];
                [self searchHistory];
                [self addHistory];
                [self loadPlayData];
            }
        }
        if (self.playMode == RandomMode) {
            self.indexRow = arc4random() % self.allMusicArray.count;
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            [self givePicToplayButtonWhenPlay];
            [self loadPlayData];
            [self searchHistory];
            [self addHistory];
        }
        if (self.playMode == OneSongMode) {
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            [self givePicToplayButtonWhenPlay];
            [self loadPlayData];
        }
    }
    //当是播放状态时
    else{
        if (self.playMode == OrderMode){
            self.indexRow++;
            //   判断当前是否是最后一曲,如果是最后一曲,点击后重新播放第一曲
            if (self.indexRow == self.allMusicArray.count) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
                
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                //点击下一曲重新给歌曲名和图片复制
                [self loadPlayData];
            }
        }
        if (self.playMode == RandomMode) {
            self.indexRow = arc4random() % self.allMusicArray.count;
            if (self.indexRow == self.allMusicArray.count) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
                
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                //点击下一曲重新给歌曲名和图片复制
                [self loadPlayData];
            }
        }
        if (self.playMode == OneSongMode) {
            if (self.indexRow == self.allMusicArray.count) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                //点击下一曲重新给歌曲名和图片复制
                [self loadPlayData];
            }
        }
    }
    [self searchHistory];
    [self addHistory];
}
/** 摇一摇结束（需要在这里处理结束后的代码） */
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    // 不是摇一摇运动事件
    if (motion != UIEventSubtypeMotionShake) return;
    NSLog(@"motionEnded");
}

/** 摇一摇取消（被中断，比如突然来电） */
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"motionCancelled");
}

#pragma mark 给播放按钮图片
-(void)givePicToplayButtonWhenPlay{
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
}
#pragma mark 给暂停按钮图片
-(void)givePicToplayButtonWhenPause{
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
}
#pragma mark 重写播放网址的set方法
-(void)setPlayUrl:(NSString *)playUrl{
    if (_playUrl == playUrl) {
        return;
    }else{
        _playUrl = playUrl;
        [self secondGiveData];
        
        [self loadPlayData];
    }
}
#pragma mark 点上一曲或下一曲重新给歌曲名和图片复制
-(void)secondGiveData{
    self.headTitleNameLabel.text = [[self.allMusicArray objectAtIndex:self.indexRow] name];
    [self.headPicImageView sd_setImageWithURL:[NSURL URLWithString:[[self.allMusicArray objectAtIndex:self.indexRow] pic]] placeholderImage:[UIImage imageNamed:@"mine"]];
    [self.backImageView sd_setImageWithURL:[NSURL URLWithString:[[self.allMusicArray objectAtIndex:self.indexRow] pic]] placeholderImage:nil];
}
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, WIDTH / 375 * 200, WIDTH , HEIGHT / 667 * 250) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.scrollEnabled = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = HEIGHT / 667 * 50;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView registerClass:[LCPlayerTbCell class] forCellReuseIdentifier:@"lcplaytbcell"];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.titleNameArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LCPlayerTbCell *cell = [tableView dequeueReusableCellWithIdentifier:@"lcplaytbcell"];
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.nameLabel.text = [self.titleNameArr objectAtIndex:indexPath.row];
    if (indexPath.row == 0) {
        cell.enterImageView.hidden = YES;
        cell.musicNameLabel.text = [[self.allMusicArray objectAtIndex:self.indexRow] name];
        UIImageView *imageOne = [[UIImageView alloc] initWithFrame:CGRectMake(20 * WIDTH / 375, 12 * HEIGHT / 667, 20 * WIDTH / 375, 20 * HEIGHT / 667)];
        [imageOne setImage:[UIImage imageNamed:@"mine"]];
        [cell addSubview:imageOne];
        
    }
    if (indexPath.row == 2) {
        UIImageView *imageTwo = [[UIImageView alloc] initWithFrame:CGRectMake(20 * WIDTH / 375, 14 * HEIGHT / 667, 20 * WIDTH / 375, HEIGHT / 667)];
        [imageTwo setImage:[UIImage imageNamed:@"mine"]];
        [cell addSubview:imageTwo];
       
    }if (indexPath.row == 3) {
        UIImageView *imageThree = [[UIImageView alloc] initWithFrame:CGRectMake(20 * WIDTH / 375, 14 * HEIGHT / 667, 20 * WIDTH / 375, 20 * HEIGHT / 667)];
        [imageThree setImage:[UIImage imageNamed:@"mine"]];
        [cell addSubview:imageThree];
            }if (indexPath.row == 4) {
        UIImageView *imageFour = [[UIImageView alloc] initWithFrame:CGRectMake(20 * WIDTH / 375, 14 * HEIGHT / 667, 20 * WIDTH / 375, 20 * HEIGHT / 667)];
        [imageFour setImage:[UIImage imageNamed:@"mine"]];
        [cell addSubview:imageFour];
        
    }
    if (indexPath.row == 1) {
        UIImageView *imageFour = [[UIImageView alloc] initWithFrame:CGRectMake(20 * WIDTH / 375, 14 * HEIGHT / 667, 20 * WIDTH / 375, 20 * HEIGHT / 667)];
        [imageFour setImage:[UIImage imageNamed:@"mine"]];
        [cell addSubview:imageFour];
        
    }
    return cell;
}
#pragma mark tableView点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.row == 2) {
//        CXSelectSaveViewController *saveController = [[CXSelectSaveViewController alloc] init];
//        [self.navigationController pushViewController:saveController animated:NO];
//       
//    }
//    if (indexPath.row == 4) {
////        [UMSocialSnsService presentSnsIconSheetView:self
////                                             appKey:@"5624fd7367e58ed46e007285"
////                                          shareText:[NSString stringWithFormat:@"%@ 你要分享的歌曲:", self.playUrl]
////                                         shareImage:[UIImage imageNamed:@"icon.png"]
////                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToQQ,nil]
////                                           delegate:nil];
//    }
//    if (indexPath.row == 3) {
//        CXHistoryViewController *histoty = [[CXHistoryViewController alloc] init];
//        
//        [self.navigationController pushViewController:histoty animated:NO];
//        [histoty release];
//    }
//    if (indexPath.row == 1) {
//        CXReconmandViewController *reconmand = [[CXReconmandViewController alloc] init];
//        
//        //        [self.navigationController pushViewController:reconmand animated:NO];
//        [self presentViewController:reconmand animated:YES completion:nil];
//        //        [reconmand release];
//        
//    }
}
- (void)startTime
{
    self.musicTime = [NSTimer scheduledTimerWithTimeInterval:0.04 target:self selector:@selector(time) userInfo:nil repeats:YES];
}
- (void)time
{
    self.headPicImageView.transform = CGAffineTransformRotate(self.headPicImageView.transform, 2 * M_PI / 360 * 1);
}
-(void)viewWillAppear:(BOOL)animated{
    
    self.tabBarController.tabBar.hidden = YES;
    
    //让计时器开始
    [self.musicTime setFireDate:[NSDate distantPast]];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
//    [self search];
    [self.tableView reloadData];
    if (self.tempArray != nil) {
        self.saveButton.selected = NO;
    }
    for (Lcdada *tempModel in self.tempArray) {
        if ([tempModel.source isEqualToString:self.playUrl]) {
            [self.saveButton setSelected:YES];
            break;
        }else{
            [self.saveButton setSelected:NO];
        }
    }
    [self secondGiveData];
    //判断当前播放是否是将要传进来得歌曲，如果是，直接返回，不是就把button状态改了
    if (self.playUrl == [[self.allMusicArray objectAtIndex:self.indexRow] source]){
        if (self.player.state == STKAudioPlayerStatePaused) {
            [self.nowPlayLable setText:@"播放暂停"];
            [self givePicToplayButtonWhenPause];
        }
        if(self.player.state == STKAudioPlayerStatePlaying)
        {
            [self.nowPlayLable setText:@"正在播放"];
            [self givePicToplayButtonWhenPlay];
        }
        else{
            if (self.playUrl == [[self.allMusicArray objectAtIndex:self.indexRow] source]){
                [self givePicToplayButtonWhenPlay];
                [self.nowPlayLable setText:@"正在播放"];
            }else{
                [self givePicToplayButtonWhenPause];
                [self.nowPlayLable setText:@"播放暂停"];
            }
        }
        return;
    }
    //拔掉耳机播放
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}
//-(void)viewWillDisappear:(BOOL)animated{
//    if (self.playUrl == [[self.allMusicArray objectAtIndex:self.indexRow] source]){
//        if (self.player.state == STKAudioPlayerStatePaused) {
//            [self givePicToplayButtonWhenPause];
//        }
//        if(self.player.state == STKAudioPlayerStatePlaying)
//        {
//            [self givePicToplayButtonWhenPlay];
//        }
//        else{
//        }
//        return;
//    }
//    //让计时器结束
//    [self.musicTime setFireDate:[NSDate distantFuture]];
//    
//    //拔掉耳机
//    [super viewWillDisappear:animated];
//    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
//    [self resignFirstResponder];
//#warning
//    [self resignFirstResponder];
//    [super viewWillDisappear:animated];
//    
//    self.tabBarController.tabBar.hidden = NO;
//}
//拔掉耳机
- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        switch (receivedEvent.subtype) {
            case UIEventSubtypeRemoteControlPause:
                [self playButtonClicked:self.playButton];
                break;
            case UIEventSubtypeRemoteControlPlay:
                [self playButtonClicked:self.playButton];
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                [self previousButtonClicked:self.previousButton];
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                [self nextButtonClicked:self.nextButton];
                break;
            default:
                break;
        }
    }
}
#pragma mark SKT代理方法 歌曲完成加载,可以控制音量什么的
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject *)queueItemId
{
    NSLog(@"完成加载");
    audioPlayer.state = STKAudioPlayerStateStopped;
    if (audioPlayer.state == STKAudioPlayerStateStopped) {
        if (!self.player) {
            return;
        }
        //顺序播放
        if (self.playMode == OrderMode) {
            if (self.indexRow == self.allMusicArray.count - 1) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
            }
        }
        //随机播放
        if (self.playMode == RandomMode) {
            self.indexRow = arc4random() % self.allMusicArray.count;
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            [self loadPlayData];
        }
        //单曲循环
        if (self.playMode == OneSongMode) {
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            [self loadPlayData];
        }
    }
    [self searchHistory];
    [self addHistory];
    
    
}
// 查看播放的开始歌曲是否存在,如果不存在运行切换歌曲的代码
-(void)audioPlayer:(STKAudioPlayer *)audioPlayer didStartPlayingQueueItemId:(NSObject *)queueItemId
{
    NSLog(@"开始播放");
}
// 播放状态改变, 暂停或者是播放, 这里可以写之前的播放的状态是单曲还是顺序
-(void)audioPlayer:(STKAudioPlayer *)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousStat
{
    NSLog(@"播放状态改变");
    [self search];
}
// 当歌曲结束的时候走这个方法
-(void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishPlayingQueueItemId:(NSObject *)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    NSLog(@"结束播放");
    NSLog(@"结束原因:%d, progress: %f, duration: %f", stopReason, progress, duration);
}

// 不怎么用到
-(void)audioPlayer:(STKAudioPlayer *)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode
{
    NSLog(@"错误原因:%d", errorCode);
}
//#pragma mark 查
-(void)search{
    if (self.tempArray != nil) {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Lcdada" inManagedObjectContext:self.manager.managedObjectContext];
        [fetchRequest setEntity:entity];
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"source"
                                                                       ascending:YES];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
        NSError *error = nil;
        NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        self.tempArray = fetchedObjects;
        NSLog(@"%@", self.tempArray);
        if (fetchedObjects == nil) {
        }else{
        }
    }
}

-(void)searchHistory{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Lchao" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"source"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    self.searchHistoryArray = fetchedObjects;
    NSLog(@"!!!!!!!!!!!dfsgdffh!!!!!!!!%@", self.searchHistoryArray);
    if (fetchedObjects == nil) {
        
    }else{
        
    }
}

-(void)viewWillDisappear:(BOOL)animated{
     self.tabBarController.tabBar.hidden = NO;
    if (self.playUrl == [[self.allMusicArray objectAtIndex:self.indexRow] source]){
        if (self.player.state == STKAudioPlayerStatePaused) {
            [self givePicToplayButtonWhenPause];
        }
        if(self.player.state == STKAudioPlayerStatePlaying)
        {
            [self givePicToplayButtonWhenPlay];
        }
        else{
        }
        return;
    }
    //让计时器结束
    [self.musicTime setFireDate:[NSDate distantFuture]];
    
    //拔掉耳机
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
#warning
    [self resignFirstResponder];
    [super viewWillDisappear:animated];
    
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
